package cn.com.ylpw.web.util;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

import cn.com.ylpw.spring.SpringContextHolder;
import cn.com.ylpw.sso.client.CasPrincipal;
import cn.com.ylpw.utils.StringUtils;
import cn.com.ylpw.utils.WebUtils;
import cn.com.ylpw.web.common.service.ICommonService;

public class ServletUtil {
	 public static final Logger log = LoggerFactory.getLogger(ServletUtil.class);
	
	/**
	 * 获取当前登陆用户基本信息
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2015年5月26日下午2:55:05
	 * @return
	 */
	public static Map<String,Object> getCustomer(HttpSession session){
		Object customerId = session.getAttribute("customerId");
		if(StringUtils.isBlank(customerId) && StringUtils.isBlank(CasPrincipal.getLoginName())){
			return Maps.newHashMap();
		}
		ICommonService commonService = SpringContextHolder.getBean("commonService");
		Map<String,Object> query = Maps.newHashMap();
		customerId = StringUtils.isBlank(customerId)?CasPrincipal.getLoginName():customerId;
		query.put("loginName", customerId);
		try {
			Map<String,Object> customer =  commonService.getCustmoerByLogin(query);
			WebUtils.getHttpServletRequest().getSession().setAttribute("customerId", customerId);
			return customer;
		} catch (Exception e) {
			log.warn("获取用户信息异常{}",query, e);
		}
		return Maps.newHashMap();
	}
	
	/**
	 * 获取当前登陆用户ID
	 * @author July july_sky@foxmail.com
	 * @date 2015年10月23日下午1:32:36
	 * @return
	 */
	public static Integer getCustomerId(HttpSession session){
		Object customersId = session.getAttribute("customerId");
		//如果session中用户ID不为空
		if (!StringUtil.isEmpty(customersId)) {
			//将用户ID放到Cookie中
			Cookie cusCookie = new Cookie("customersId", customersId.toString());
			cusCookie.setMaxAge(60*30); //Cookie生存时间30分钟
		//如果session中用户ID为空
		}else {
			try {
				log.info("session中没有读取到用户改从cookie中读取----");
				//从Cookie中取用户ID
				customersId = OrderUtils.getCookie(WebUtils.getHttpServletRequest(), "customersId");
				log.info("cookie中用户ID为:{}",customersId);
			} catch (Exception e) {

			}
		}
		return StringUtils.isBlank(customersId)?null:Integer.valueOf(customersId.toString());
	}
}
